'use client';

import { useEffect, useState } from "react";
import { Table, message, Button, Modal, Form, Radio, Input, Tag, Spin, Pagination } from "antd";
import { useUser } from "../../context/userContext";
import api from "../../utils/api";
import styles from '@/components/Font.module.css';

export default function PostManagementPage() {
    const [reports, setReports] = useState([]);
    const [totalReports, setTotalReports] = useState(0);
    const { user } = useUser();
    const [resolveReportModalVisible, setResolveReportModalVisible] = useState(false);
    const [selectedReport, setSelectedReport] = useState(null);
    const [resolveForm] = Form.useForm();
    const accessToken = user ? user.access_token : "";
    const [loading, setLoading] = useState(false);

    // 分页相关状态
    const [reportsPage, setReportsPage] = useState(1);
    const [reportsPageSize, setReportsPageSize] = useState(5);

    const fetchReports = async (page = 1, pageSize = 10) => {
        setLoading(true);
        try {
            const response = await api.get("/reports/list", {
                params: { page, pageSize },
                headers: { Authorization: `Bearer ${accessToken}` },
            });
            if (!response.data || !Array.isArray(response.data.Report)) {
                console.error("举报列表数据格式错误，Report 不是数组:", response.data);
            }
            setReports(response.data.Report || []);
            setTotalReports(response.data.total || 0);
        } catch (error) {
            console.log(error, "获取举报列表失败");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchReports(reportsPage, reportsPageSize);
    }, [reportsPage, reportsPageSize]);

    const handleResolveReport = async () => {
        try {
            const values = await resolveForm.validateFields();
            const { id: reportId } = selectedReport;

            const response = await api.post("http://120.26.138.4:3000/reports/resolve",
                {
                    reportId,
                    result: values.result,
                    reason: values.reason
                },
                { headers: { Authorization: `Bearer ${accessToken}` } }
            );

            if (response.status === 201) {
                message.success("举报处理成功");
                setResolveReportModalVisible(false);
                // 重新获取数据
                fetchReports(reportsPage, reportsPageSize);
            } else {
                message.error("举报处理失败，请重试");
            }
        } catch (error) {
            console.error("处理举报请求失败", error);
            message.error("处理举报时发生网络错误，请检查网络连接");
        }
    };

    const reportColumns = [
        { 
            title: "举报ID", 
            dataIndex: "id", 
            key: "id",
            className: styles.text,
            width: 100,
        },
        { 
            title: "举报理由", 
            dataIndex: "reason", 
            key: "reason",
            className: styles.text,
            width: 200,
        },
        { 
            title: "举报类型", 
            dataIndex: "type", 
            key: "type",
            className: styles.text,
            width: 120,
        },
        { 
            title: "被举报项ID", 
            dataIndex: "reportedItemId", 
            key: "reportedItemId",
            className: styles.text,
            width: 120,
        },
        { 
            title: "状态", 
            dataIndex: "status", 
            key: "status",
            className: styles.text,
            width: 100,
            render: (status) => (
                <Tag 
                    color={status === 'pending' ? '#D6A7A1' : status === 'resolved' ? '#52c41a' : '#ff4d4f'} 
                    style={{ fontFamily: 'var(--font-secondary)', fontSize: 14 }}
                >
                    {status === 'pending' ? '待处理' : status === 'resolved' ? '已处理' : '已驳回'}
                </Tag>
            )
        },
        {
            title: "操作",
            key: "action",
            className: styles.text,
            width: 120,
            render: (_, record) => (
                <Button
                    type="primary"
                    className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                    onClick={() => {
                        setSelectedReport(record);
                        setResolveReportModalVisible(true);
                        resolveForm.resetFields();
                    }}
                >
                    处理
                </Button>
            ),
        },
    ];

    const reportPagination = {
        current: reportsPage,
        pageSize: reportsPageSize,
        total: totalReports,
        onChange: (page, pageSize) => {
            setReportsPage(page);
            setReportsPageSize(pageSize);
            fetchReports(page, pageSize);
        },
    };

    return (
        <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6 h-full flex flex-col">
            {/* 固定标题区域 */}
            <div className="mb-4">
                <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>举报管理</h2>
            </div>

            {/* 表格容器 - 固定表头，内容可滚动 */}
            <div className="flex-1 overflow-hidden mt-2 mb-4 bg-white rounded-xl shadow-sm">
                <Spin spinning={loading}>
                    <Table
                        columns={reportColumns}
                        dataSource={reports}
                        pagination={false} // 移除内置分页，使用自定义固定分页
                        className="bordered={false}"
                        rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-[#F4EDEB]/50'}
                        size="middle"
                        scroll={{ y: "calc(100vh - 300px)" }} // 设置表格内容区域的最大高度
                        components={{
                            header: {
                                cell: ({ className, ...restProps }) => (
                                    <th
                                        {...restProps}
                                        className={`${className} ${styles.titlesmall} text-base font-semibold text-[#7A6E6E] bg-[#F4EDEB] sticky top-0 z-10`}
                                    />
                                ),
                            },
                        }}
                    />
                </Spin>
            </div>

            {/* 固定分页区域 */}
            <div className="flex justify-center">
                <Pagination
                    current={reportsPage}
                    pageSize={reportsPageSize}
                    total={totalReports}
                    onChange={reportPagination.onChange}
                    className="bg-white p-3 rounded-lg shadow-sm"
                />
            </div>

            {/* 处理举报模态框 */}
            <Modal
                title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>处理举报</span>}
                visible={resolveReportModalVisible}
                onCancel={() => setResolveReportModalVisible(false)}
                footer={[
                    <Button 
                        key="cancel" 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => setResolveReportModalVisible(false)}
                    >
                        取消
                    </Button>,
                    <Button 
                        key="ok" 
                        type="primary"
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={handleResolveReport}
                    >
                        确认处理
                    </Button>,
                ]}
                className="rounded-xl overflow-hidden bg-[#F4EDEB]"
                style={{ borderRadius: '16px' }}
                centered
            >
                <div className="p-4 bg-white rounded-lg shadow-sm">
                    <div className="mb-4 pb-2 border-b border-gray-200">
                        <div className={`${styles.text} font-medium text-gray-700`}>举报信息</div>
                        <div className={`${styles.text} text-sm text-gray-500 mt-1`}>
                            <div>举报ID: {selectedReport?.id}</div>
                            <div>举报类型: {selectedReport?.type}</div>
                            <div>被举报项ID: {selectedReport?.reportedItemId}</div>
                            <div>举报理由: {selectedReport?.reason}</div>
                        </div>
                    </div>
                    
                    <Form form={resolveForm} layout="vertical" className="mt-2">
                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>处理结果</span>}
                            name="result"
                            rules={[{ required: true, message: "请选择处理结果" }]}
                        >
                            <Radio.Group>
                                <Radio value="accepted">接受举报（Accepted）</Radio>
                                <Radio value="rejected">驳回举报（Rejected）</Radio>
                            </Radio.Group>
                        </Form.Item>

                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>处理理由</span>}
                            name="reason"
                            rules={[{ required: true, message: "请输入处理理由" }]}
                        >
                            <Input.TextArea 
                                rows={3} 
                                placeholder="请输入详细处理理由" 
                                className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all"
                            />
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
        </div>
    );
}